package pers.zc.activiti.netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @description
 * @Author Lin FuYuan
 * @date 2020/7/2
 */
public class EchoClientHandler extends ChannelInboundHandlerAdapter {
    private final ByteBuf message;

    public EchoClientHandler() {
        message = Unpooled.buffer(256);
        message.writeBytes("hello   ".getBytes(CharsetUtil.UTF_8));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
//        Scanner s = new Scanner(System.in);
//        if(s.hasNext()){
//            String next = s.next();
//            System.out.println(next);
//            ctx.writeAndFlush(next);
//        }
//        s.close();
        ctx.writeAndFlush(message);
    }

    /**
     * 接收数据时调用
     *
     * @param ctx
     * @param msg
     * @return void
     * @author Lin FuYuan
     * @date 2020/7/2
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("Client channel Read " + ((ByteBuf) msg).toString(CharsetUtil.UTF_8));
        ctx.write(msg);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        System.out.println("client channel complete" + ctx);
        ctx.flush();
    }

    /**
     * 处理异常时调用
     *
     * @param ctx
     * @param cause
     * @return void
     * @author Lin FuYuan
     * @date 2020/7/2
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}
